# 作业：
# 1、写函数,将传入的列表或元祖对象的奇数位索引对应的元素
"""
def get_odd_index_elements(input_list_or_tuple):

    odd_index_elements = input_list_or_tuple[1::2]
    return odd_index_elements

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = get_odd_index_elements(my_list)
print(result)
"""
# 2、写函数,判断用户传入的对象(string,list,tuple)长度是否大于5
"""
def is_length_greater_than_five(obj):
    length = len(obj)
    return length > 5
string_example = "example"
list_example = [1, 2, 3, 4, 5, 6]
tuple_example = (1, 2, 3, 4, 5, 6, 7)

print(is_length_greater_than_five(string_example))
print(is_length_greater_than_five(list_example))
print(is_length_greater_than_five(tuple_example))
"""
# 3、写函数,计算传入的string中,数字,字母,空格以及其它内容的个数,并返回结果
"""
def count_characters(input_string):
    digit_count = 0
    letter_count = 0
    space_count = 0
    other_count = 0

    for char in input_string:
        if char.isdigit():
            digit_count += 1
        elif char.isalpha():
            letter_count += 1
        elif char.isspace():
            space_count += 1
        else:
            other_count += 1

    return {
        'digit_count': digit_count,
        'letter_count': letter_count,
        'space_count': space_count,
        'other_count': other_count
    }
input_str = "Hello 123 World! 456"
result = count_characters(input_str)
print(result)
"""
# 4、写函数,接收 两个数字参数,返回较大的那个数字
"""
def find_larger_number(num1, num2):
    # 使用条件表达式比较两个数字的大小
    return num1 if num1 > num2 else num2

result = find_larger_number(5, 10)
print(result)  # 输出 10
"""
# 5、编写一个函数cacluate, 可以接收任意多个数,返回的是一个元组.
"""
def calculate(*args):
    result_tuple = tuple(args)
    return result_tuple

result = calculate(1, 2, 3, 4, 5)
print(result)
"""
# 6、编写一个函数, 接收字符串参数, 返回一个元组,元组的第一个值为大写字母的个数, 第二个值为小写字母个数.
"""
def count_upper_lower(input_string):
    upper_count = 0
    lower_count = 0

    for char in input_string:
        if char.isupper():
            upper_count += 1
        elif char.islower():
            lower_count += 1

    return (upper_count, lower_count)
input_str = "Hello World"
result = count_upper_lower(input_str)
print(result)
def count_upper_lower(input_string):
    upper_count = 0
    lower_count = 0
    for char in input_string:
        if char.isupper():
            upper_count += 1
        elif char.islower():
            lower_count += 1
    return (upper_count, lower_count)
input_str = "Hello World"
result = count_upper_lower(input_str)
print(result)
"""
# 7、编写函数, 接收一个列表(包含30个1~100之间的随机整形数)和一个整形数k, 返回一个新列表.
# 函数需求:
# 将列表下标k之前对应(不包含k)的元素逆序;
"""
def reverse_elements_before_k(lst, k):
    if k >= len(lst) or k < 0:
        print("Error: Index out of range.")
        return None
    reversed_elements = lst[:k][::-1]
    return reversed_elements + lst[k:]
import random
random_numbers = [random.randint(1, 100) for _ in range(30)]
k_value = 15
result_list = reverse_elements_before_k(random_numbers, k_value)
print("Original List:", random_numbers)
print("Result List:", result_list)
"""
# 将下标k及之后的元素逆序;
"""
def reverse_elements_after_k(lst, k):
    if k >= len(lst) or k < 0:
        print("Error: Index out of range.")
        return None
    reversed_elements = lst[k:][::-1]
    return lst[:k] + reversed_elements
import random
random_numbers = [random.randint(1, 100) for _ in range(30)]
k_value = 15
result_list = reverse_elements_after_k(random_numbers, k_value)
print("Original List:", random_numbers)
print("Result List:", result_list)
"""
# 8、编写函数，从键盘输入参数x和n，计算并显示形如x+xx +xxx + xxxx + xxxxx+xxx…xxx+ 的表达式前n项的值
"""
def calculate_expression(x, n):
    result = 0
    current_term = 0

    for i in range(1, n + 1):
        current_term = current_term * 10 + x
        result += current_term

    return result
x = int(input("请输入x的值："))
n = int(input("请输入n的值："))
expression_result = calculate_expression(x, n)
print(f"表达式前{n}项的值为：{expression_result}")
"""
# 9、写函数,函数接收的4个参数分别是:姓名,性别(默认为男),年龄,地址
"""
def display_person_info(name, age, address, gender='男'):
    print("姓名:", name)
    print("性别:", gender)
    print("年龄:", age)
    print("地址:", address)
name_input = input("请输入姓名: ")
age_input = int(input("请输入年龄: "))
address_input = input("请输入地址: ")
gender_input = input("请输入性别(默认为男，按回车键跳过): ")
if gender_input.strip():
    display_person_info(name_input, age_input, address_input, gender_input)
else:
    display_person_info(name_input, age_input, address_input)
"""
# 10、写函数,接收n个数字,返回这些数字的和(动态传参)
"""
def calculate_sum(*args):
    return sum(args)
num1 = float(input("请输入第一个数字: "))
num2 = float(input("请输入第二个数字: "))
num3 = float(input("请输入第三个数字: "))
result = calculate_sum(num1, num2, num3)
print(f"这些数字的和为: {result}")
"""
# 11、在实参中传入多个可迭代对象(要有string,list,tuple,set,dict),将每个对象的每个元素都加到args或kwargs里
"""
def process_iterables(*iterables, **kwargs):
    args = []

    for iterable in iterables:
        if isinstance(iterable, (str, list, tuple, set)):
            args.extend(iterable)
        elif isinstance(iterable, dict):
            kwargs.update(iterable)
        else:
            raise ValueError("Unsupported type of iterable")

    return args, kwargs

string_iterable = "Hello, World!"
list_iterable = [1, 2, 3, 4, 5]
tuple_iterable = (10, 20, 30)
set_iterable = {100, 200, 300}
dict_iterable = {'a': 1, 'b': 2, 'c': 3}

args_result, kwargs_result = process_iterables(string_iterable, list_iterable, tuple_iterable, set_iterable,
                                               dict_iterable)

print("args:", args_result)
print("kwargs:", kwargs_result)
"""
# 12、写函数,把传过来的列表中的每一个元素都用"_"拼接,并返回
"""
def join_elements_with_underscore(input_list):
    result = "_".join(map(str, input_list))
    return result

my_list = [1, 'apple', 3.14, 'banana']

result_string = join_elements_with_underscore(my_list)

print("拼接后的字符串:", result_string)
"""
# 13、写函数,传入一个数字,返回这个数的阶乘。示例：1x2x3....
"""
def factorial_iterative(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result
number = 5  # 要计算阶乘的数字

result = factorial_iterative(number)
print(f"{number}的阶乘为: {result}")
"""
# 14、写函数,返回一个扑克牌列表,里面有52项,每一项都是一个tuple
"""
def generate_deck():
    suits = ['♠', '♥', '♦', '♣']
    values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
    deck = [(value, suit) for suit in suits for value in values]

    return deck
deck_of_cards = generate_deck()
print("前五张牌:", deck_of_cards[:5])
"""
# 15、编写函数，求1+2+3+…N的和
"""
def sum_up_to_n_loop(n):
    result = 0
    for i in range(1, n + 1):
        result += i
    return result
number = 5

result = sum_up_to_n_loop(number)
print(f"1+2+3+...+{number} 的和为: {result}")
"""
# 16、编写一个函数，求多个数中的最大值
"""
def find_max(*args):
    if not args:
        return None

    max_value = args[0]
    for num in args:
        if num > max_value:
            max_value = num

    return max_value
result = find_max(3, 8, 1, 6, 5, 9)
print("最大值是:", result)
"""
# 17、编写一个函数，提取指定字符串中所有的字母，然后拼接在一起产生一个新的字符串
"""
def extract_and_concatenate(input_str):
    result = ''.join(char for char in input_str if char.isalpha())
    return result

input_string = "Hello 123 World!"

output_result = extract_and_concatenate(input_string)
print("提取的字母字符串:", output_result)
"""
# 18、写一个函数，求多个数的平均值
"""
def calculate_average(*args):
    if not args:
        return None

    total = sum(args)
    average = total / len(args)

    return average
result = calculate_average(3, 8, 1, 6, 5, 9)

print("平均值是:", result)
def calculate_average(*args):
    if not args or not all(isinstance(arg, (int, float)) for arg in args):
        return None
    total = sum(args)
    average = total / len(args)
    return average
numbers = [3, 8, 1, 6, 5, 9]

result = calculate_average(*numbers)
print("平均值是:", result)
"""
# 19、写一个自己的len函数，统计指定序列中元素的个数
"""
def my_len(sequence):
    count = 0
    for _ in sequence:
        count += 1
    return count

my_list = [1, 2, 3, 4, 5]
my_string = "Hello, World!"

length_of_list = my_len(my_list)
length_of_string = my_len(my_string)

print(f"列表的长度: {length_of_list}")
print(f"字符串的长度: {length_of_string}")
"""
# 20、找出传入的列表或元组的奇数位对应的元素，并返回一个新的列表
"""
def odd_position_elements(input_sequence):
    return input_sequence[1::2]

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
my_tuple = (11, 22, 33, 44, 55, 66, 77, 88, 99)

result_list = odd_position_elements(my_list)
result_tuple = odd_position_elements(my_tuple)

print("奇数位对应的元素列表:", result_list)
print("奇数位对应的元素元组:", result_tuple)
"""
# 21、水仙花数：个位、十位、百位的立方加在一起等于数的本身
"""
def find_armstrong_numbers():
    armstrong_numbers = []
    for num in range(100, 1000):
        hundreds = num // 100
        tens = (num % 100) // 10
        units = num % 10

        if num == (hundreds ** 3 + tens ** 3 + units ** 3):
            armstrong_numbers.append(num)

    return armstrong_numbers

armstrong_numbers_list = find_armstrong_numbers()
print("三位水仙花数:", armstrong_numbers_list)
"""
# 22、 定义函数，有一个形参，传入的是列表，数组大小不超过 100个，
# 数组中的每个元素值不允许超过 100，但是可以等于100，
"""
def process_array(input_array):
    if not input_array:
        print("列表为空")
        return

    if len(input_array) > 100:
        print("数组大小超过100")
        return

    if any(element > 100 for element in input_array):
        print("数组中存在元素值超过100")
        return
    print("处理合法的数组:", input_array)

valid_array = [10, 20, 30, 40, 50]
invalid_size_array = list(range(101))
invalid_value_array = [5, 10, 150, 20]

process_array(valid_array)
process_array(invalid_size_array)
process_array(invalid_value_array)
"""
# 如果列表大小超过了100个截取到第100个为止，要求返回的列表格式：
"""
def process_array(input_array):
    if not input_array:
        return "列表为空"

    truncated_array = input_array[:100]

    if any(element > 100 for element in truncated_array):
        return "截取后的数组中存在元素值超过100"

    result_string = f"原始数组: {input_array}\n处理后的数组: {truncated_array}"
    return result_string

large_array = list(range(150))

result = process_array(large_array)
print(result)
"""
# 删除所有重复元素，使得每个元素只出现一次
"""
def remove_duplicates_order_preserved(input_list):
    unique_elements = []
    for element in input_list:
        if element not in unique_elements:
            unique_elements.append(element)

    return unique_elements

my_list = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]
result_list = remove_duplicates_order_preserved(my_list)
print("去除重复元素并保留顺序的列表:", result_list)
"""
# 按照数字的大小，由高到低排序返回
"""
def sort_descending(input_list):
    sorted_list = sorted(input_list, reverse=True)

    return sorted_list

my_list = [5, 2, 8, 1, 3]

result_list = sort_descending(my_list)
print("按照数字大小降序排序的列表:", result_list)
"""
# 23、定义函数 getLength，打印用户传入的容器类型和数据长度
"""
def getLength(container):
    container_type = type(container).__name__

    try:
        length = len(container)
        print(f"容器类型: {container_type}, 长度: {length}")
    except TypeError:
        print(f"无法获取容器类型: {container_type} 的长度")

list_example = [1, 2, 3, 4, 5]
tuple_example = (10, 20, 30)
set_example = {5, 10, 15, 20}

getLength(list_example)
getLength(tuple_example)
getLength(set_example)
"""
# 24、定义函数 generateNum( )
"""
import random

def generateNum():
    random_numbers = [random.randint(1, 100) for _ in range(5)]

    print("生成的随机数字:", random_numbers)

    return random_numbers

generated_numbers = generateNum()
"""
# 25、定义函数 moreThan(num)，判断输入的数字是否大于1500
"""
def moreThan(num):
    if num > 1500:
        print(f"{num} 大于 1500")
        return True
    else:
        print(f"{num} 不大于 1500")
        return False

result = moreThan(2000)
"""
# 26、定义函数，有两个形参，第一个形参到第二个形参的范围，所有平方数之和
"""
def sum_of_squares(start, end):
    if start > end:
        print("范围无效：起始值大于结束值")
        return None

    squares = [i**2 for i in range(start, end+1)]
    sum_result = sum(squares)

    return sum_result

start_value = 1
end_value = 5

result = sum_of_squares(start_value, end_value)

if result is not None:
    print(f"{start_value} 到 {end_value} 范围内所有平方数的和为: {result}")
"""
# 27、写函数，检查传入字典的每一个value长度，如果大于2，
# 那么仅保留前两个长度的内容， 并将新内容返回给调用者
"""
def process_dict(dictionary):
    new_dict = {}
    for key, value in dictionary.items():
        if len(value) > 2:
            new_dict[key] = value[:2]
        else:
            new_dict[key] = value
    return new_dict
original_dict = {'a': 'apple', 'b': 'banana', 'c': 'cherry', 'd': 'date'}

processed_dict = process_dict(original_dict)

print("原始字典:", original_dict)
print("处理后的字典:", processed_dict)
"""
#  28、写函数，判断用户传入的对象（字符串、列表、元组）的元素是否为空
"""
def is_empty(obj):
    if not obj:
        print("对象为空")
        return True
    else:
        print("对象不为空")
        return False
empty_string = ""
non_empty_string = "Hello, World!"
empty_list = []
non_empty_list = [1, 2, 3]
empty_tuple = ()
non_empty_tuple = (4, 5, 6)

is_empty(empty_string)  
is_empty(non_empty_string)  

is_empty(empty_list)  
is_empty(non_empty_list) 

is_empty(empty_tuple)  
is_empty(non_empty_tuple) 
"""
# 29、编写自定义函数，完成一个简单的减法运算函数
"""
def subtract(a, b):
    result = a - b
    return result

num1 = 10
num2 = 5

result = subtract(num1, num2)
print(f"{num1} 减去 {num2} 的结果是: {result}")
"""
# 30、编写自定义函数，可以输出自己的名字即可。
"""
def print_my_name():
    print("你的名字")
print_my_name()
"""
# 31、编写自定义函数：剪刀石头布
# 游戏开始，初始状态下用户和电脑都有 100 分，赢一局+10 分，输一局-10 分。
#
#  当用户为 0 分时，游戏结束，提示游戏结束，比赛输了
#
# 当用户为 200 分时，游戏结束，提示游戏结束，赢得比赛、每轮比赛都输出当前的分数
#
# 1 代表剪刀 2 代表石头 3 代表布
"""
import random

def rock_paper_scissors_game():
    user_score = 100
    computer_score = 100

    while user_score > 0 and user_score < 200:
        print(f"当前分数 - 用户: {user_score}, 电脑: {computer_score}")
        user_choice = int(input("请输入你的选择（1.剪刀, 2.石头, 3.布）: "))
        computer_choice = random.randint(1, 3)

        if user_choice == computer_choice:
            print("平局，重新选择！")
        elif (user_choice == 1 and computer_choice == 3) or \
             (user_choice == 2 and computer_choice == 1) or \
             (user_choice == 3 and computer_choice == 2):
            print("你赢了这一局！")
            user_score += 10
            computer_score -= 10
        else:
            print("你输了这一局！")
            user_score -= 10
            computer_score += 10

    if user_score == 0:
        print("游戏结束，比赛输了！")
    elif user_score == 200:
        print("游戏结束，赢得比赛！")
    else:
        print("游戏结束，未知结果！")

rock_paper_scissors_game()
"""
# 32、编写一个函数，接受一个字符串作为参数，并返回该字符串的逆序字符串
"""
def reverse_string(input_str):
    return input_str[::-1]
original_string = "Hello, World!"
reversed_string = reverse_string(original_string)

print(f"原始字符串: {original_string}")
print(f"逆序字符串: {reversed_string}")
"""
# 33、编写一个函数，接受一个数字列表作为参数，并返回其中所有偶数的列表
"""
def get_even_numbers(numbers):
    even_numbers = [num for num in numbers if num % 2 == 0]
    return even_numbers

input_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = get_even_numbers(input_numbers)

print(f"原始列表: {input_numbers}")
print(f"偶数列表: {result}")
"""
# 34、编写一个函数，接受一个字符串列表作为参数，并返回其中最长的字符串。
"""
def find_longest_string(string_list):
    if not string_list:
        return None

    longest_string = max(string_list, key=len)
    return longest_string

input_strings = ["apple", "banana", "kiwi", "strawberry", "blueberry"]
result = find_longest_string(input_strings)

print(f"原始字符串列表: {input_strings}")
print(f"最长的字符串: {result}")
"""
# 35、编写一个函数，接受一个数字列表作为参数，并返回其中所有数字的平方的总和
"""
def sum_of_squares(numbers):
    return sum(num ** 2 for num in numbers)

input_numbers = [1, 2, 3, 4, 5]
result = sum_of_squares(input_numbers)

print(f"原始数字列表: {input_numbers}")
print(f"平方和: {result}")
"""
# 36、编写一个函数，接受一个字符串作为参数，并返回其中所有单词的首字母的大写形式
# def capitalize_first_letters(input_string):
#     words = input_string.split()
#
#     capitalized_words = [word.capitalize() for word in words]
#
#     result_string = ' '.join(capitalized_words)
#
#     return result_string
#
# input_str = "hello world example"
# result = capitalize_first_letters(input_str)
# print(result)
"""
def capitalize_first_letters(input_string):
    words = input_string.split()

    capitalized_words = [word.capitalize() for word in words]

    result_string = ' '.join(capitalized_words)

    return result_string

input_str = "hello world example"
result = capitalize_first_letters(input_str)
print(result)
"""
# 37、编写一个函数，接受两个列表作为参数，并返回两个列表的交集
# 举例：
# list1 = [100,200,300,454]
# list2 = [454,789,125,46]
# 返回：[454]
"""
def find_intersection(list1, list2):
    set1 = set(list1)
    set2 = set(list2)

    intersection = list(set1.intersection(set2))

    return intersection

list1 = [100, 200, 300, 454]
list2 = [454, 789, 125, 46]

result = find_intersection(list1, list2)
print(result)
"""
#  38、定义一个学生注册函数enroll()，打印学生姓名，性别，年龄，城市， 使用默认参数降低调用函数的复杂度
"""
def enroll(name, gender='man', age=24, city='CN'):
    print(f"学生姓名: {name}")
    print(f"性别: {gender}")
    print(f"年龄: {age}")
    print(f"城市: {city}")

enroll("张三")
"""
